package com.zzyl.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.member.domain.dto.ReservationDto;
import com.zzyl.member.domain.pojo.Reservation;
import com.zzyl.member.mapper.SubscribeNursingMapper;
import com.zzyl.member.service.SubscribeNursingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class SubscribeNursingServiceImpl extends ServiceImpl<SubscribeNursingMapper, Reservation> implements SubscribeNursingService {
    @Autowired
    private SubscribeNursingMapper subscribeNursingMapper;
    @Override
    public void add(ReservationDto dto) {
        Reservation reservation = BeanUtil.toBean(dto, Reservation.class);
        reservation.setStatus(0);
        reservation.setCreateTime(LocalDateTime.now());
        this.save(reservation);
    }

    @Override
    public IPage<Reservation> getPageMy(Integer pageNum, Integer pageSize, Integer status) {
        Page<Reservation> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Reservation> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtil.isNotEmpty(status), Reservation::getStatus, status);
        return subscribeNursingMapper.selectPage(page, wrapper); // 使用selectPage
    }

    @Override
    public Long serachcanCelledCount() {
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        long count = this.count(Wrappers.<Reservation>lambdaQuery().eq(Reservation::getId, UserThreadLocal.get()).eq(Reservation::getStatus, 2).between(Reservation::getUpdateBy, startTime, endTime));

        return count;
    }

    @Override
    public void cancel(Long id) {
        Reservation reservation = new Reservation();
        reservation.setId(id);
        reservation.setStatus(2);
        this.updateById(reservation);
    }

    @Override
    public List<Map<String, Object>> countByTime() {
        List<Map<String, Object>> result = subscribeNursingMapper.selectMaps(
                Wrappers.<Reservation>query()
                        .select("time, COUNT(*) as count")
                        .groupBy("time")
        );
        return result;
    }
}
